package com.trimer.rpc.core.config;

import com.trimer.rpc.core.RpcService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Component
@Lazy(true)
public class RpcAnnotationScannerConfigurer implements BeanDefinitionRegistryPostProcessor {

    private Map<String, Object> rpcServiceBeanMap = new HashMap<>();

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
        registBeanByClazz(arg0, RpcService.class);
    }

    private <T extends RpcService> void registBeanByClazz(ConfigurableListableBeanFactory arg0, Class<T> var1) {
        Map<String, Object> serviceBeanMap = arg0.getBeansWithAnnotation(var1);

        if (serviceBeanMap != null && !serviceBeanMap.isEmpty()) {
            for (Object serviceBean : serviceBeanMap.values()) {
                T rpcService = serviceBean.getClass().getAnnotation(var1);
                //拿到注解的名称
                String serviceName = rpcService.value().getName();
                String serviceVersion = rpcService.version();
                if (!StringUtils.isEmpty(serviceVersion)) {
                    serviceName += "-" + serviceVersion;
                }
                rpcServiceBeanMap.put(serviceName, serviceBean);
            }
        }
    }

    public Map<String, Object> getRpcServiceBeanMap() {
        return rpcServiceBeanMap;
    }

    public void setRpcServiceBeanMap(Map<String, Object> rpcServiceBeanMap) {
        this.rpcServiceBeanMap = rpcServiceBeanMap;
    }

    public Object getRpcServiceBean(String  rpcServiceBeanName) {
        return rpcServiceBeanMap.get(rpcServiceBeanName);
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry arg0) throws BeansException {
        // TODO Auto-generated method stub

    }
}